package com.keyingbo.websocket.controller;

import com.keyingbo.websocket.dto.LoginDto;
import com.keyingbo.websocket.dto.UserDto;
import com.keyingbo.websocket.server.WebSocketKeepOneLoginServer;
import com.keyingbo.websocket.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    ScheduledExecutorService service = Executors.newScheduledThreadPool(4);

    @Autowired
    private WebSocketKeepOneLoginServer webSocketKeepOneLoginServer;

    private static Map<String, UserDto> userDtoMap = new HashMap<>();
    static {
        //用户集合
        userDtoMap.put("user001" ,UserDto.builder().userId("user001").psw("user001").userName("用户1").build());
        userDtoMap.put("user002" ,UserDto.builder().userId("user002").psw("user002").userName("用户2").build());
        userDtoMap.put("user003" ,UserDto.builder().userId("user003").psw("user003").userName("用户3").build());
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request,LoginDto loginDto) {
        String result = "loginerror";
        if (StringUtils.isEmpty(loginDto.getUserId())) {
            request.setAttribute("error", "用户ID不能为空");
            return result;
        }
        if (!userDtoMap.containsKey(loginDto.getUserId())) {
            request.setAttribute("error", "用户ID或密码不正常");
            return result;
        }
        UserDto userDto = userDtoMap.get(loginDto.getUserId());
        if (!userDto.getPsw().equals(loginDto.getPsw())) {
            request.setAttribute("error", "用户ID或密码不正常");
            return result;
        }
        //登录成功
        TokenUtil.resetUserAndToken(userDto.getUserId());
        //返回token
        request.setAttribute("token" , TokenUtil.getToken(userDto.getUserId()));
        //通知踢除其他端登录
        //延时3秒执行
        service.schedule(() ->{
            webSocketKeepOneLoginServer.noticeToOtherWeb(userDto.getUserId());
        }, 3 , TimeUnit.SECONDS);

        result = "loginsucess";
        return result;
    }

    @RequestMapping("index")
    public String index(HttpServletRequest request, @RequestParam("token") String token) {
        request.setAttribute("token" , token);
        return "index";
    }
}
